﻿Imports System
Imports IDServer
Imports System.Threading.Thread
Imports System.IO
Imports System.String
Imports Microsoft.VisualBasic
Imports Microsoft.VisualBasic.VBMath
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports CalendarColumn

Public Class Frm_SALRetailGift
    Implements IDServer.IDServer.IDServer
    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Public mDS As DataSet  '新增表單的的資料集
    Private dsBSC As DataSet  '存放公共資料
    Private ds As New DataSet  '瀏覽表單的資料集
    Private strOriginalNum As String = ""
    Private tempDS As New DataSet
    Private bFind As Boolean
    Private Fields As String
    Private WithEvents MainFrom As Frm_MainForm
    Private CaptionStr As String = "禮券編號^Num&名稱^CName&有效日期從^StartDate&有效日期至^EndDate&面值^FaceAmount&相關號碼^RefNum&狀態^Status"
    Private CaptionStr1 As String = "序號^SN&禮券編號^Num&名稱^CName&有效日期從^StartDate&有效日期至^EndDate&面值^FaceAmount&相關號碼^RefNum&狀態^Status"
    Private strBillstatusID = ""
    Private mPoint As Point
    Private X, Y As Integer


#Region "inteface define"
    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainFrom
        End Get
        Set(ByVal value As Frm_MainForm)
            MainFrom = value
        End Set
    End Property

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        Try
            If AddEnable = False Then
                MessageBox.Show(My.resources.notallowadd, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Me.Cursor = Cursors.WaitCursor
            ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd

            EnabledControls(True)
            Me.dgrd2.ReadOnly = True

            Me.TabControl1.SelectedIndex = 1

            ClearText()

            SetButton(ButtonType.Add, False)

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Try
            Dim Num As String
            ClearText()
            EnabledControls(False)

            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp

            If ds Is Nothing Then
                Exit Function
            End If

            IsFind = FindRecord()
            SetButton(ButtonType.Cancel, IsFind)

            If ds.Tables.Count = 0 Then
                Exit Function
            End If
            If Me.ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            IsFind = FindRecord()
            SetButton(ButtonType.Cancel, IsFind)

            If Me.dgrd1.SelectedCells.Count > 0 Then
                Num = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value
                FillText(Num)
            End If
            GetToolEnable()

        Catch ex As Exception
            MessageBox.Show("ActionCancel:" + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete
        If DeleteEnable = False Then
            MessageBox.Show(My.Resources.NotAllowDelete, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        Dim cnSqlServer As New SqlConnection
        cnSqlServer = GetConn()
        Dim cmdSqlServer As New SqlCommand
        Dim trnSqlServer As SqlTransaction = cnSqlServer.BeginTransaction
        Dim strNum As String
        Dim iIndex As Integer

        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            strNum = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value
            iIndex = Me.dgrd1.CurrentRow.Index
            If MsgBox("確實要禮券：" & strNum & "嗎？", MsgBoxStyle.Question Or MessageBoxButtons.YesNo, "資訊提示") = MsgBoxResult.Yes Then
                With cmdSqlServer
                    .Connection = cnSqlServer
                    .Transaction = trnSqlServer
                    .CommandType = CommandType.Text

                    '刪除記錄
                    .CommandText = "DELETE BSC_Gift  WHERE Num='" & strNum & "'"
                    .ExecuteNonQuery()

                End With
                trnSqlServer.Commit()


                '清空DS中相關記錄
                Dim rows() As DataRow = ds.Tables(0).Select("Num='" & strNum & "'")
                If rows.Length > 0 Then
                    For Each row As DataRow In rows
                        row.Delete()

                    Next
                End If

                ds.AcceptChanges()

                IsFind = FindRecord()
                SetButton(ButtonType.Browse, IsFind)
                MessageBox.Show(My.resources.DeleteSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                trnSqlServer.Rollback()
            End If
            GetToolEnable()
        Catch ex As Exception
            trnSqlServer.Rollback()
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)

        End Try
    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        Try
            If EditEnable = False Then
                MessageBox.Show(My.resources.NotAllowEidt, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If


            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            If Me.dgrd1.SelectedCells.Count = 0 Then
                Exit Function
            End If

            If Me.TabControl1.SelectedIndex = 0 Then
                Me.TabControl1.SelectedIndex = 1
            End If

            If Me.dgrd1.SelectedCells.Count > 0 Then
                Dim Num As String = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value
                FillText(Num)
            End If

            ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
            EnabledControls(True)
            SetButton(ButtonType.Edit, False)

            strOriginalNum = Me.txtNum.Text
        Catch ex As Exception
            MsgBox("ActionEdit:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Try
            If App.ExportEnable = False Then
                MessageBox.Show(My.resources.NotAllowExport, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            Me.Cursor = Cursors.WaitCursor
            If FindRecord() = False Then
                Exit Function
            Else

                'Dim tb As DataTable '猁換腔桶

                Dim dsTemp As DataSet = ds.Copy
                '將列名改為中文名
                For I As Integer = Me.dgrd1.Columns.Count - 1 To 0 Step -1
                    Dim strName As String = Me.dgrd1.Columns(I).Name
                    dsTemp.Tables(0).Columns(strName).Caption = Me.dgrd1.Columns(strName).HeaderText
                    '移除不需要顯示的列
                    If Me.dgrd1.Columns(I).Visible = False Then
                        dsTemp.Tables(0).Columns.Remove(strName)
                    End If
                Next


                '將表名改為中文名
                dsTemp.Tables(0).TableName = "禮券明細"


                SaveXls(dsTemp)

            End If
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            Dim row As Integer = Me.dgrd1.CurrentCell.RowIndex

            If Me.dgrd1.RowCount > 0 And Me.dgrd1.CurrentRow.Index > 0 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(0).Cells(0)
                If Me.TabControl1.SelectedIndex = 1 Then
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                        FillText(Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value)
                    End If
                End If

            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast
        Try
            If ds Is Nothing Then
                Exit Function
            End If
            Dim row As Integer = Me.dgrd1.CurrentCell.RowIndex

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            If Me.dgrd1.RowCount > 0 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(Me.dgrd1.Rows.Count - 1).Cells(0)
                If Me.TabControl1.SelectedIndex = 1 Then
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                        FillText(Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value)
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            Dim row As Integer = Me.dgrd1.CurrentCell.RowIndex

            If Me.dgrd1.RowCount > 0 And Me.dgrd1.CurrentRow.Index < Me.dgrd1.Rows.Count - 1 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(row + 1).Cells(0)
                If Me.TabControl1.SelectedIndex = 1 Then
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                        FillText(Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value)
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            Dim row As Integer = Me.dgrd1.CurrentCell.RowIndex

            If Me.dgrd1.RowCount > 0 And Me.dgrd1.CurrentRow.Index > 0 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(row - 1).Cells(0)
                If Me.TabControl1.SelectedIndex = 1 Then
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                        FillText(Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value)
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If Me.txtNum.Text = "" Then
                    MsgBox(GetMsg("PUR", "NotNullValue"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.txtNum.Focus()
                    Return False
                End If

                '判斷有效日期是否有效
                If CDate(Me.dtStartDate.Text) >= CDate(Me.dtEndDate.Text) Then
                    MsgBox(GetMsg("BSC", "NotValidDate"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.dtEndDate.Focus()
                    Return False
                End If

            ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                If Me.dgrd2.Rows.Count = 1 And Me.dgrd2.Rows(0).IsNewRow = True Then
                    Return False
                End If

                '迴圈判斷值是否有效
                'Num, CName, StartDate, EndDate, FaceAmount, RefNum, Status
                For I As Integer = 0 To dgrd2.Rows.Count - 1
                    If dgrd2.Rows(I).IsNewRow = False Then

                        If dgrd2.Rows(I).Cells("Num").Value Is Nothing Then
                            MsgBox(GetMsg("PUR", "NotNullValue"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            dgrd2.CurrentCell = dgrd2.Rows(I).Cells("Num")
                            Return False
                        End If

                        If dgrd2.Rows(I).Cells("Num").Value.ToString.Trim = "" Then
                            MsgBox(GetMsg("PUR", "NotNullValue"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            dgrd2.CurrentCell = dgrd2.Rows(I).Cells("Num")
                            Return False
                        End If

                        If dgrd2.Rows(I).Cells("CName").Value Is Nothing Then
                            MsgBox(GetMsg("PUR", "NotNullValue"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            dgrd2.CurrentCell = dgrd2.Rows(I).Cells("CName")
                            Return False
                        End If

                        If dgrd2.Rows(I).Cells("CName").Value.ToString.Trim = "" Then
                            MsgBox(GetMsg("PUR", "NotNullValue"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            dgrd2.CurrentCell = dgrd2.Rows(I).Cells("CName")
                            Return False
                        End If

                        If CDate(CDate(dgrd2.Rows(I).Cells("StartDate").Value).ToShortDateString) < CDate(Now.ToShortDateString) Then
                            MsgBox(GetMsg("PUR", "NotValidDate"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            dgrd2.CurrentCell = dgrd2.Rows(I).Cells("StartDate")
                            Return False
                        End If

                        If CDate(CDate(dgrd2.Rows(I).Cells("StartDate").Value).ToShortDateString) >= CDate(CDate(dgrd2.Rows(I).Cells("EndDate").Value).ToShortDateString) Then
                            MsgBox(GetMsg("BSC", "NotValidDate"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            dgrd2.CurrentCell = dgrd2.Rows(I).Cells("EndDate")
                            Return False
                        End If


                        If dgrd2.Rows(I).Cells("FaceAmount").Value Is Nothing Then
                            MsgBox(GetMsg("PUR", "NotNullValue"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            dgrd2.CurrentCell = dgrd2.Rows(I).Cells("FaceAmount")
                            Return False
                        End If

                        If dgrd2.Rows(I).Cells("FaceAmount").Value.ToString.Trim = "" Then
                            MsgBox(GetMsg("PUR", "NotNullValue"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            dgrd2.CurrentCell = dgrd2.Rows(I).Cells("FaceAmount")
                            Return False
                        End If

                        If dgrd2.Rows(I).Cells("Status").Value Is Nothing Then
                            dgrd2.Rows(I).Cells("Status").Value = "未使用"
                            Return False
                        End If

                    End If
                Next


            End If

            Return True
        Catch ex As Exception

            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Return False
        End Try
    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        Try
            If ActionInitialize() = False Then Exit Function

            If BtnActionSave() = True Then
                IsFind = FindRecord()
                SetButton(ButtonType.Browse, IsFind)
                Return True
            Else
                'IsFind = FindRecord()
                'SetButton(ButtonType.Browse, IsFind)
                Return False
            End If
        Catch ex As Exception
            MsgBox("ActionSave:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect
        Filter()
    End Function

#End Region


#Region "Windows Sub"

    Private Sub Frm_SALRetailGift_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            '設置gbxBatch位置
            With Me.gbxBatch
                .Top = Me.gbxOne.Top
                .Left = Me.gbxOne.Left
            End With

            Me.dtStartDate1.Value = Now
            Me.dtEndDate1.Value = Now
            'Me.dtStartDate1.Checked = False
            Me.dtEndDate1.Checked = False

            '綁定並格式化dgrd1
            DataBindGrid(Me.dgrd1, CaptionStr)
            BindGridCaption(Me.dgrd1, BindHashTable(CaptionStr))

            With Me.dgrd1
                .ReadOnly = True
                .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing
                .SelectionMode = DataGridViewSelectionMode.CellSelect
                .MultiSelect = False
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ReadOnly = True
            End With

            ReBindControls()
            '' LoadMultiLanguage()

            '設置dgrd2
            dgrdAddCol(dgrd2)
            With Me.dgrd2
                .ReadOnly = True
                .EditMode = DataGridViewEditMode.EditOnEnter
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .MultiSelect = True
            End With

            Me.cmbStatus1.Text = "未使用"


            EnabledControls(False)
            Me.BtnFind.Enabled = FindEnable
            ReadDgrdStyle(Me)
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub
    Private Sub DataGridView1_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles dgrd1.DataError
        Try

        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    ''' <summary>
    ''' 選擇批量生成禮券
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub radBatch_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radBatch.CheckedChanged
        Try
            Me.gbxBatch.Visible = Me.radBatch.Checked
            Me.gbxOne.Visible = Not Me.radBatch.Checked

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 選擇逐條生成禮券
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub radOne_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radOne.CheckedChanged
        Try
            Me.gbxOne.Visible = Me.radOne.Checked
            Me.gbxBatch.Visible = Not Me.radOne.Checked

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 是否允許直接修改禮券資料
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub chkAllowEdit_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkAllowEdit.CheckedChanged
        Try
            If chkAllowEdit.Checked = True Then
                With Me.dgrd2
                    .ReadOnly = False
                    .Columns("SN").ReadOnly = True
                    .Columns("RefNum").ReadOnly = True
                    .Columns("Status").ReadOnly = True
                    .SelectionMode = DataGridViewSelectionMode.CellSelect
                    .MultiSelect = False
                End With

            Else
                With Me.dgrd2
                    .ReadOnly = True
                    .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                    .MultiSelect = True

                End With
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtNum1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtNum1.KeyDown, _
       txtNum2.KeyDown, dtStartDate1.KeyDown, dtEndDate1.KeyDown, txtCName1.KeyDown, txtCName2.KeyDown, cmbFaceAmount1.KeyDown, cmbFaceAmount2.KeyDown, _
       cmbStatus1.KeyDown, txtNum.KeyDown, txtCName.KeyDown, cmbFaceAmount.KeyDown, dtStartDate.KeyDown, dtEndDate.KeyDown, _
       chkAllowEdit.KeyDown, radBatch.KeyDown, radOne.KeyDown, dtStartDate2.KeyDown, dtEndDate2.KeyDown, cmbFaceAmount3.KeyDown, _
       txtNum3.KeyDown, txtCName3.KeyDown, txtPrefix.KeyDown, nudLength.KeyDown, nudStart.KeyDown, nudEnd.KeyDown, _
       nudQTY.KeyDown, cmbFaceAmount3.KeyDown, cmbStatus.KeyDown
        Try
            If e.KeyCode = Keys.Shift Then
                e.Handled = True
                If e.KeyCode = Keys.Enter Then
                    SendKeys.Send("+{TAB}")
                    SendKeys.Send("{F4}")
                End If
            Else
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        SendKeys.Send("{TAB}")
                        SendKeys.Send("{F4}")
                End Select
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub dgrd1_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgrd1.CurrentCellChanged
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim mytb As New DataTable
            'Dim sql As String
            Dim Num As String
            If Me.dgrd1.DataSource Is Nothing Then
                Exit Sub
            End If

            If Me.dgrd1.SelectedCells.Count <= 0 Then
                Exit Sub

            End If

            If Me.dgrd1.CurrentCell Is Nothing Then
                Exit Sub
            End If

            Num = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells("Num").Value
            If Num Is Nothing Then
                Exit Sub
            Else
                strBillstatusID = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells("Status").Value

                If Not (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit) Then
                    IsFind = FindRecord()
                    SetButton(ButtonType.Browse, IsFind)
                End If


            End If
            GetToolEnable()
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub dgrd1_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgrd1.DoubleClick
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Exit Sub
            End If
            If ds.Tables.Count = 0 Then
                Exit Sub
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Sub
            End If

            If Me.TabControl1.SelectedIndex = 0 Then
                'Me.TabControl1.SelectedIndex = 1
                If IsDBNull(Me.dgrd1.Rows(0).Cells(0).Value) Then
                    Exit Sub
                Else
                    Dim Num As String = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells("Num").Value

                    If Not (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit) Then
                        FillText(Num)
                    End If

                End If
                Me.TabControl1.SelectedIndex = 1
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        Try
            Me.Cursor = Cursors.WaitCursor

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Exit Sub
            End If
            If ds Is Nothing Then
                Exit Sub
            End If

            If ds.Tables.Count = 0 Then
                Exit Sub
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Sub
            End If

            If Me.TabControl1.SelectedIndex = 1 Then
                If Me.dgrd1.SelectedCells.Count > 0 Then
                    Dim Num As String = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value
                    FillText(Num)
                End If
            End If

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub nudQTY_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudQTY.ValueChanged
        Try
            Me.nudEnd.Value = Me.nudStart.Value + Me.nudQTY.Value - 1
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub nudEnd_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudEnd.ValueChanged
        Try
            Me.nudQTY.Value = Me.nudEnd.Value - Me.nudStart.Value + 1
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub nudStart_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudStart.ValueChanged
        Try
            Me.nudEnd.Minimum = Me.nudStart.Value
            Me.nudEnd.Value = Me.nudStart.Value + Me.nudQTY.Value
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub TabControl1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TabControl1.KeyDown
        Try

            If e.KeyCode = Keys.Shift Then
                e.Handled = True
                If e.KeyCode = Keys.Enter Then
                    SendKeys.Send("+{TAB}")
                    SendKeys.Send("{F4}")
                End If
            Else
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        SendKeys.Send("{TAB}")
                        SendKeys.Send("{F4}")
                End Select
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub dgrd2_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrd2.RowLeave
        Try
            UpdateSN()
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim strNum, strCName, strFaceAmount, strPrefix As String
            Dim dtStart, dtEnd As DateTime
            Dim intLength, intStart, intEnd, intQTY, intRowIndex As Integer

            If dgrd2.Rows.Count = 1 Then
                intRowIndex = 0
            ElseIf dgrd2.CurrentRow Is Nothing Then
                intRowIndex = dgrd2.Rows.Count - 1
            Else
                intRowIndex = dgrd2.CurrentRow.Index
            End If

            dtStart = Me.dtStartDate2.Value
            dtEnd = Me.dtEndDate2.Value
            strFaceAmount = Me.cmbFaceAmount3.Text.Trim
            strCName = Me.txtCName3.Text.Trim

            strPrefix = Me.txtPrefix.Text.Trim & ""
            intLength = Me.nudLength.Value
            intStart = Me.nudStart.Value
            intEnd = Me.nudEnd.Value
            intQTY = Me.nudQTY.Value


            '判斷有效日期是否有效
            If CDate(Me.dtStartDate2.Text) < CDate(Now.ToShortDateString) Then
                MsgBox(GetMsg("PUR", "NotValidDate"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.dtStartDate2.Focus()
                Return
            End If

            If CDate(Me.dtStartDate2.Text) >= CDate(Me.dtEndDate2.Text) Then
                MsgBox(GetMsg("BSC", "NotValidDate"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.dtEndDate2.Focus()
                Return
            End If

            If Me.txtCName3.Text.Replace("'", "").Trim = "" Then
                MsgBox(GetMsg("BSC", "NotNullGiftCName"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.txtCName3.Focus()
                Return

            End If


            '如果采用批量生成條碼
            If Me.radBatch.Checked = True Then
                '判斷編號長度是否有效
                If strPrefix.Length + intEnd.ToString.Length > intLength Then
                    MsgBox(GetMsg("PUR", "NotValidLength"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.nudLength.Focus()
                    Return
                End If

                Me.Progressbar1.Visible = True

                '迴圈插入禮券號
                For I As Integer = intStart To intEnd
                    strNum = strPrefix + Microsoft.VisualBasic.StrDup((intLength - strPrefix.Length) - Len((I).ToString), "0") + I.ToString
                    If CountDatGridViewRecode(dgrd2, "Num", strNum) = 0 Then
                        dgrd2.Rows.Add("", strNum, strCName, dtStart, dtEnd, strFaceAmount, "", "未使用")
                    End If
                    Me.Progressbar1.Value = (I - intStart + 1) / intQTY * 100
                Next

                Me.Progressbar1.Visible = False
                UpdateSN()

            Else
                '採用逐條輸入

                If Me.txtNum3.Text.Replace("'", "").Trim = "" Then
                    MsgBox(GetMsg("BSC", "NotNullGiftNum"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.txtNum3.Focus()
                    Me.dtEndDate.Value = Now
                    Return

                End If


                '判斷禮券號碼是否重復
                strNum = Me.txtNum3.Text.Trim

                If CountDatGridViewRecode(dgrd2, "Num", strNum) >= 1 Then
                    MsgBox(GetMsg("PUR", "RepetitionRecord"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Return
                End If

                dgrd2.Rows.Insert(intRowIndex, "", strNum, strCName, dtStart, dtEnd, strFaceAmount, "", "未使用")
                'dgrd2.Rows.Add("", strNum, strCName, dtStart, dtEnd, strFaceAmount, "", "未使用")
                UpdateSN()
                dgrd2.Refresh()


            End If
        Catch ex As Exception
            Me.Progressbar1.Visible = False
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub btnDelAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelAll.Click
        Try
            Me.dgrd2.Rows.Clear()
            UpdateSN()

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        Try
            For I As Integer = Me.dgrd2.SelectedRows.Count - 1 To 0 Step -1
                If dgrd2.SelectedRows(I).IsNewRow = False Then
                    Me.dgrd2.Rows.Remove(dgrd2.SelectedRows(I))
                End If

            Next

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind.Click
        MainFrom.ToolStripFind_Click(Nothing, Nothing)

    End Sub

    Private Function BtnActionSave() As Boolean

        Dim cnSqlServer As New SqlConnection
        cnSqlServer = GetConn()
        Dim cmdSqlServer As New SqlCommand
        Dim trnSqlServer As SqlTransaction = cnSqlServer.BeginTransaction

        Try

            Dim strNum, strCName, strStatus As String
            Dim dtStartDate, dtEndDate As String
            Dim intFaceAmount As Integer


            '當是添加保存
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then

                With cmdSqlServer
                    .Connection = cnSqlServer
                    .Transaction = trnSqlServer
                    .CommandType = CommandType.Text

                    '向BSC_Gift插入記錄
                    For I As Integer = 0 To dgrd2.Rows.Count - 1
                        If dgrd2.Rows(I).IsNewRow = False Then
                            strNum = dgrd2.Rows(I).Cells("Num").Value.ToString.Replace("'", "")
                            strCName = dgrd2.Rows(I).Cells("CName").Value.ToString.Replace("'", "")
                            dtStartDate = CDate(CDate(dgrd2.Rows(I).Cells("StartDate").Value).ToShortDateString)
                            dtEndDate = CDate(CDate(dgrd2.Rows(I).Cells("EndDate").Value).ToShortDateString)
                            intFaceAmount = CInt(dgrd2.Rows(I).Cells("FaceAmount").Value)
                            .CommandText = "INSERT INTO BSC_Gift (Num, CName, StartDate, EndDate, FaceAmount," & _
                                           " Status, BulidDate, LastUpdateDate, BulidComputer," & _
                                           "LastUpdateComputer, BulidBy, LastUpdateBy) " & _
                                           " VALUES ('" & strNum & "','" & strCName & "','" & dtStartDate & "','" & _
                                           dtEndDate & "'," & intFaceAmount & ",0,convert(varchar(19),getdate(),120)," & _
                                           "Convert(varchar(19), getdate(), 120),host_name(),host_name(),'" & _
                                           PubUserName & "','" & PubUserName & "')"
                            .ExecuteNonQuery()

                        End If
                    Next

                    '向ds添加記錄
                    If ds Is Nothing Then
                        Initialize()
                    End If

                    If ds.Tables.Count = 0 Then
                        Initialize()
                    End If

                    For I As Integer = 0 To dgrd2.Rows.Count - 1
                        If dgrd2.Rows(I).IsNewRow = False Then
                            strNum = dgrd2.Rows(I).Cells("Num").Value.ToString.Replace("'", "")
                            strCName = dgrd2.Rows(I).Cells("CName").Value.ToString.Replace("'", "")
                            dtStartDate = CDate(CDate(dgrd2.Rows(I).Cells("StartDate").Value).ToShortDateString)
                            dtEndDate = CDate(CDate(dgrd2.Rows(I).Cells("EndDate").Value).ToShortDateString)
                            intFaceAmount = CInt(dgrd2.Rows(I).Cells("FaceAmount").Value)
                            strStatus = dgrd2.Rows(I).Cells("Status").Value

                            Dim mRow As DataRow
                            mRow = ds.Tables(0).NewRow
                            mRow("Num") = strNum
                            mRow("CName") = strCName
                            mRow("StartDate") = dtStartDate
                            mRow("EndDate") = dtEndDate
                            mRow("FaceAmount") = intFaceAmount
                            mRow("Status") = strStatus

                            ds.Tables(0).Rows.Add(mRow)
                            ds.Tables(0).AcceptChanges()

                        End If
                    Next

                End With
                ClearText()


            Else

                '修改記錄
                With cmdSqlServer
                    .Connection = cnSqlServer
                    .Transaction = trnSqlServer
                    .CommandType = CommandType.Text


                    '1.更新Gift記錄
                    strNum = Me.txtNum.Text.ToString.Replace("'", "")
                    strCName = Me.txtCName.Text.ToString.Replace("'", "")
                    dtStartDate = Me.dtStartDate.Text
                    dtEndDate = Me.dtEndDate.Text
                    intFaceAmount = CInt(Me.cmbFaceAmount.Text)
                    strStatus = Me.cmbStatus.Text

                    'Num, CName, StartDate, EndDate, FaceAmount, RefNum, Status
                    .CommandText = "UPDATE BSC_Gift SET Num='" & strNum & _
                      "',CName='" & strCName & _
                      "',StartDate='" & dtStartDate & _
                      "',EndDate='" & dtEndDate & _
                      "',FaceAmount=" & intFaceAmount & _
                      ",LastUpdateDate=convert(varchar(19),getdate(),120)" & _
                      ",LastUpdateComputer=host_name()" & _
                      ",LastUpdateBy='" & PubUserName & "'" & _
                      " WHERE Num='" & strOriginalNum & "'"


                    .ExecuteNonQuery()

                End With

                '修改ds記錄

                If ds Is Nothing Then Exit Function
                Dim Rows() As DataRow = ds.Tables(0).Select("Num='" & strOriginalNum & "'")
                If Rows.Length > 0 Then
                    For Each row As DataRow In Rows
                        row("Num") = strNum
                        row("CName") = strCName
                        row("StartDate") = dtStartDate
                        row("EndDate") = dtEndDate
                        row("FaceAmount") = intFaceAmount
                    Next
                End If

                ds.AcceptChanges()



            End If
            EnabledControls(False)

            trnSqlServer.Commit()

            MsgBox(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.Resources.AddSuccess, My.Resources.EditSuccess), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            GetToolEnable()
            Return True
        Catch ex As Exception
            trnSqlServer.Rollback()
            If Microsoft.VisualBasic.InStr(ex.Message, "违反了 PRIMARY KEY 约束") > 0 Then

                MsgBox(GetMsg("PUR", "ExistSameRecord"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Else
                MsgBox("BtnActionSave:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If

            Return False

        End Try
    End Function

    Private Sub dgrd1_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgrd1.RowPostPaint
        Try
            Dim rectangle As New Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, Me.dgrd1.RowHeadersWidth - 4, e.RowBounds.Height)
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), Me.dgrd1.RowHeadersDefaultCellStyle.Font, _
               rectangle, dgrd1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.Right)

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub mnuSaveStyle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSaveStyle.Click
        SaveDgrdStyle(Me)
    End Sub

    Private Sub mnuDelStyle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDelStyle.Click
        DeldgvStyle(Me)
    End Sub

#End Region


#Region "Function Define"

    ''' <summary>
    ''' 設置DataGridView的列標題
    ''' </summary>
    ''' <param name="dgrd"></param>
    ''' <param name="caption"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function setDgrdCol(ByVal dgrd As DataGridView, ByVal caption As String)
        Try
            Dim Str() As String = caption.Split("&")
            '如果DataGridView沒有列，則添加列
            If dgrd.Columns.Count = 0 Then
                For i As Integer = 0 To Str.Length - 1
                    Dim strName, strHeaderText As String
                    strName = Str(i).Split("^")(1)
                    strHeaderText = Str(i).Split("^")(0)
                    dgrd.Columns.Add(strName, strHeaderText)

                Next
            Else '否則修改列標題
                For i As Integer = 0 To Str.Length - 1
                    Dim strName, strHeaderText As String
                    strName = Str(i).Split("^")(0)
                    strHeaderText = Str(i).Split("^")(1)
                    dgrd.Columns(strName).HeaderText = strHeaderText

                Next

            End If


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    ''' <summary>
    ''' 設置Dgrd的列
    ''' </summary>
    ''' <param name="dgrd">DataGridView</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function dgrdAddCol(ByVal dgrd As DataGridView) As Boolean
        '序號^SN&禮券編號^Num&名稱^CName&有效日期從^StartDate&有效日期至^EndDate&
        '面值^FaceAmount&相關號碼^RefNum&狀態^Status
        Try
            Dim colSN As New DataGridViewTextBoxColumn
            With colSN
                .Name = "SN"
                .HeaderText = "序號"
                .Width = 60

            End With
            dgrd.Columns.Add(colSN)

            Dim colNum As New DataGridViewTextBoxColumn
            With colNum
                .Name = "Num"
                .HeaderText = "禮券編號"
            End With
            dgrd.Columns.Add(colNum)

            Dim colCName As New DataGridViewTextBoxColumn
            With colCName
                .Name = "CName"
                .HeaderText = "名稱"
            End With
            dgrd.Columns.Add(colCName)

            Dim colStartDate As New CalendarColumn.CalendarColumn()
            With colStartDate
                .Name = "StartDate"
                .HeaderText = "有效日期從"
                .Width = 72
                .ValueType = GetType(Date)
            End With
            dgrd.Columns.Add(colStartDate)

            Dim colEndDate As New CalendarColumn.CalendarColumn()
            With colEndDate
                .Name = "EndDate"
                .HeaderText = "有效日期至"
                .Width = 72
                .ValueType = GetType(Date)
            End With
            dgrd.Columns.Add(colEndDate)

            Dim colFaceAmount As New DataGridViewComboBoxColumn
            With colFaceAmount
                For I As Integer = 0 To dsBSC.Tables(0).Rows.Count - 1
                    .Items.Add(dsBSC.Tables(0).Rows(I).Item("ListA"))

                Next

                .Width = 60
                .Name = "FaceAmount"
                .HeaderText = "面值"
            End With
            dgrd.Columns.Add(colFaceAmount)

            Dim colRefNum As New DataGridViewTextBoxColumn
            With colRefNum
                .Name = "RefNum"
                .HeaderText = "相關號碼"

            End With
            dgrd.Columns.Add(colRefNum)

            Dim colStatus As New DataGridViewComboBoxColumn
            With colStatus
                .Items.Add("未使用")
                .Items.Add("已使用")
                .Width = 72
                .Name = "Status"
                .HeaderText = "狀態"

            End With
            dgrd.Columns.Add(colStatus)

            Me.dgrd2.Columns("Num").Frozen = True


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    ''' <summary>
    ''' 重新綁定控制項的資料源
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ReBindControls()
        Try
            GetPublic()

            '綁定數據
            With Me.cmbFaceAmount1
                .DataSource = dsBSC.Tables("FaceAmountType1")
                .ValueMember = ("ListCode")
                .DisplayMember = ("ListA")
            End With

            With Me.cmbFaceAmount2
                .DataSource = dsBSC.Tables("FaceAmountType2")
                .ValueMember = ("ListCode")
                .DisplayMember = ("ListA")
            End With

            With Me.cmbFaceAmount
                .DataSource = dsBSC.Tables("FaceAmountType")
                .ValueMember = ("ListCode")
                .DisplayMember = ("ListA")
            End With

            With Me.cmbFaceAmount3
                .DataSource = dsBSC.Tables("FaceAmountType3")
                .ValueMember = ("ListCode")
                .DisplayMember = ("ListA")
            End With

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try


    End Sub

    ''' <summary>
    ''' 獲取公共資料
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub GetPublic()
        Try

            Dim Table(3) As String
            Dim sql(3) As String

            '禮券面值類型
            Table(0) = "FaceAmountType"
            sql(0) = "select ListCode,ListA from dbo.BSC_OtherDefineB " & _
                     " where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='FaceAmountType') " & _
                     " ORDER BY ListCode"

            '禮券面值類型1
            Table(1) = "FaceAmountType1"
            sql(1) = "select '' ListCode,'' ListA   union " & _
                     "select ListCode,ListA from dbo.BSC_OtherDefineB " & _
                     " where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='FaceAmountType') " & _
                     " ORDER BY ListCode"

            '禮券面值類型2
            Table(2) = "FaceAmountType2"
            sql(2) = "select '' ListCode,'' ListA   union " & _
                     "select ListCode,ListA from dbo.BSC_OtherDefineB " & _
                     " where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='FaceAmountType') " & _
                     " ORDER BY ListCode"

            '禮券面值類型3
            Table(3) = "FaceAmountType3"
            sql(3) = "select ListCode,ListA from dbo.BSC_OtherDefineB " & _
                     " where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='FaceAmountType') " & _
                     " ORDER BY ListCode"

            dsBSC = GetDataSet(sql, Table)

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 設置控件的Enable屬性
    ''' </summary>
    ''' <param name="B"></param>
    ''' <remarks></remarks>
    Private Sub EnabledControls(ByVal B As Boolean)
        Try
            Me.Panel4.Enabled = B
            Me.Panel5.Enabled = B
            Me.dgrd2.ReadOnly = Not B

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try




    End Sub

    ''' <summary>
    ''' 過濾符合條件的記錄
    ''' </summary>
    ''' <remarks></remarks>
    Sub Filter()
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Exit Sub
            End If

            Me.Cursor = Cursors.WaitCursor
            Dim dt1, dt2 As String
            Dim intStatus As Integer
            dt1 = Me.dtStartDate1.Value.Year.ToString + "/" + Me.dtStartDate1.Value.Month.ToString + "/" + Me.dtStartDate1.Value.Day.ToString
            dt2 = Me.dtEndDate1.Value.Year.ToString + "/" + Me.dtEndDate1.Value.Month.ToString + "/" + Me.dtEndDate1.Value.Day.ToString

            Dim Table(0) As String
            Dim sql(0) As String
            sql(0) = "select  a.Num, a.CName, a.StartDate, a.EndDate, FaceAmount=b.ListA, IsNull(a.RefNum,'') RefNum," & _
             "    Status=CASE a.Status WHEN 0 THEN '未使用' ELSE '已使用' END " & _
             " from BSC_Gift a left join (select ListCode,ListA from dbo.BSC_OtherDefineB " & _
             "   where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='FaceAmountType'))b " & _
             "  on convert(nvarchar(20),a.FaceAmount)=b.ListCode  WHERE 1=1 "

            If Me.dtStartDate1.Checked = True Then
                sql(0) += "and a.StartDate >='" & dt1 & "'"
            End If

            If Me.dtEndDate1.Checked = True Then
                sql(0) += " and a.EndDate<='" & dt2 & "' "
            End If

            '禮券單號
            If Me.txtNum1.TextLength > 0 Then
                sql(0) += " and a.Num>='" & Me.txtNum1.Text & "' "
            End If

            If Me.txtNum2.TextLength > 0 Then
                sql(0) += " and a.Num<='" & Me.txtNum2.Text & "' "
            End If

            ' 禮券名稱
            If Me.txtCName1.TextLength > 0 Then
                sql(0) += " and a.CName>='" & Me.txtCName1.Text & "' "
            End If

            If Me.txtCName2.TextLength > 0 Then
                sql(0) += " and a.CName<='" & Me.txtCName2.Text & "' "
            End If


            '禮券面值
            If Me.cmbFaceAmount1.Text.Length > 0 Then
                sql(0) += " and a.FaceAmount>='" & Me.cmbFaceAmount1.SelectedValue & "' "
            End If

            If Me.cmbFaceAmount2.Text.Length > 0 Then
                sql(0) += " and a.FaceAmount<='" & Me.cmbFaceAmount2.SelectedValue & "' "
            End If

            '單據狀態
            If Me.cmbStatus1.Text.Length > 0 Then
                If Me.cmbStatus1.Text = "已使用" Then
                    intStatus = 1
                Else
                    intStatus = 0
                End If
                sql(0) += " and a.status=" & intStatus
            End If

            sql(0) += " Order by a.Num"

            Table(0) = "BSC_Gift"


            ds = GetDataSet(sql, Table)

            Me.dgrd1.DataSource = ds.Tables("BSC_Gift")
            bFind = ds.Tables(0).Rows.Count > 0

            IsFind = FindRecord()

            If IsFind = False Then
                MsgBox(Msg.NotFindRecord, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If


            SetButton(ButtonType.Browse, IsFind)
            GetToolEnable()

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)

        Finally
            Me.Cursor = Cursors.Default
        End Try


    End Sub

    ''' <summary>
    ''' 判斷是否有記錄
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FindRecord() As Boolean

        If ds Is Nothing Then
            Return False
            Exit Function
        End If

        If Me.dgrd1.Rows.Count = 0 Then
            Return False
        Else
            Return True

        End If

    End Function

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type"></param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try
            MainFrom.ToolStripCheck.Enabled = False
            MainFrom.ToolStripUnCheck.Enabled = False
            Select Case type

                Case ButtonType.Add
                    With MainFrom
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Browse
                    With MainFrom
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind And strBillstatusID = "未使用"
                        .ToolStripDelete.Enabled = IsFind And strBillstatusID = "未使用"
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Cancel
                    With MainFrom
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind And strBillstatusID = "未使用"
                        .ToolStripDelete.Enabled = IsFind And strBillstatusID = "未使用"
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Edit
                    With MainFrom
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 從DataGridView選定記錄後填充Text
    ''' </summary>
    ''' <param name="Num"></param>
    ''' <remarks></remarks>
    Private Sub FillText(ByVal Num As String)
        Try
            ClearText()
            '禮券編號^Num&名稱^CName&有效日期從^StartDate&有效日期至^EndDate&面值^FaceAmount&相關號碼^RefNum&狀態^Status

            Dim mRow() As DataRow = ds.Tables(0).Select("Num='" & Num & "'")
            If mRow Is Nothing Then Exit Sub
            For Each Row As DataRow In mRow
                Me.txtNum.Text = Row("Num") & ""
                Me.txtCName.Text = Row("CName") & ""
                Me.dtStartDate.Value = Row("StartDate") & ""
                Me.dtEndDate.Value = Row("EndDate") & ""
                Me.cmbFaceAmount.Text = Row("FaceAmount") & ""
                Me.cmbStatus.Text = Row("Status") & ""
            Next

            UpdateSN()

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' ClearText()
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ClearText()
        Try
            Me.txtNum.Text = ""
            Me.txtCName.Text = ""
            Me.cmbFaceAmount.Text = "50"
            Me.cmbFaceAmount3.Text = "50"
            Me.cmbStatus.Text = "未使用"
            Me.dtStartDate.Value = Now
            Me.dtEndDate.MinDate = "1900/1/1"
            Me.dtEndDate.Value = Now
            Me.dtEndDate.MinDate = "1900/1/1"
            Me.chkAllowEdit.Checked = False

            If Me.dgrd2.Rows.Count > 1 Then
                Me.dgrd2.Rows.Clear()
            End If



            Me.radBatch.Checked = True
            Me.dtStartDate2.Value = Now
            Me.dtStartDate2.MinDate = "1900/1/1"
            Me.dtEndDate2.Value = Now
            Me.dtEndDate2.MinDate = "1900/1/1"
            Me.cmbFaceAmount3.Text = "50"


            Me.txtNum3.Text = ""
            Me.txtCName3.Text = ""
            Me.txtPrefix.Text = ""
            Me.nudLength.Value = 1
            Me.nudStart.Value = 0
            Me.nudEnd.Minimum = 0
            Me.nudEnd.Value = 0
            Me.nudQTY.Value = 1


            If mDS IsNot Nothing Then
                If mDS.Tables.Count > 0 Then
                    mDS.Tables(0).Rows.Clear()
                End If
            End If

            UpdateSN()

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 更新行號
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub UpdateSN()
        Try

            For I As Integer = 0 To Me.dgrd2.Rows.Count - 1
                With Me.dgrd2
                    .Item("SN", I).Value = Microsoft.VisualBasic.StrDup(5 - Len((I + 1).ToString), "0") + (I + 1).ToString
                End With
            Next

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 查找DataGridView中某欄位的相同記錄數
    ''' </summary>
    ''' <param name="dgrd">需要統計的DataGridview</param>
    ''' <param name="colName">要統計的列名</param>
    ''' <param name="Key">要統計的值</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CountDatGridViewRecode(ByVal dgrd As DataGridView, ByVal colName As String, ByVal Key As String) As Integer
        Try
            Dim intCount As Integer = 0
            If dgrd.Rows.Count = 0 Then
                Return intCount
                Exit Function
            End If


            For I As Integer = 0 To dgrd.Rows.Count - 1
                If dgrd.Rows(I).Cells(colName).Value = Key Then
                    intCount += 1
                End If
            Next

            Return intCount

        Catch ex As Exception
            Return -1
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    ''' <summary>
    '''  初始化ds
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Initialize()
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim Table(0) As String
            Dim sql(0) As String
            sql(0) = "select  a.Num, a.CName, a.StartDate, a.EndDate, FaceAmount=b.ListA, IsNull(a.RefNum,'') RefNum," & _
             "    Status=CASE a.Status WHEN 0 THEN '未使用' ELSE '已使用' END " & _
             " from BSC_Gift a left join (select ListCode,ListA from dbo.BSC_OtherDefineB " & _
             "   where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='FaceAmountType'))b " & _
             "  on convert(nvarchar(20),a.FaceAmount)=b.ListCode  WHERE 1=2 "

            Table(0) = "BSC_Gift"


            ds = GetDataSet(sql, Table)
            Me.dgrd1.DataSource = ds.Tables("BSC_Gift")


            IsFind = FindRecord()

            SetButton(ButtonType.Browse, IsFind)

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default

        End Try

    End Function

    Private Sub GetToolEnable()
        Try
            With MainFrom
                .ToolStripAdd.Enabled = AddEnable
                .ToolStripEdit.Enabled = EditEnable
                .ToolStripDelete.Enabled = DeleteEnable
                .ToolStripPrint.Enabled = PrintEnable
                .ToolStripImport.Enabled = ImportEnable
                .ToolStripExport.Enabled = ExportEnable
                .ToolStripFind.Enabled = FindEnable
                .ToolStripCheck.Enabled = CheckEnable And ModSys.isInterfaceMethodFinished(Me, "ActionChecked")
                .ToolStripUnCheck.Enabled = UncheckEnable And ModSys.isInterfaceMethodFinished(Me, "ActionUnchecked")
                .ToolStripComplete.Enabled = CompleteEnable And ModSys.isInterfaceMethodFinished(Me, "ActionComplete")
                .AddToolStripMenuItem.Enabled = .ToolStripAdd.Enabled
                .Edit1ToolStripMenuItem.Enabled = .ToolStripEdit.Enabled
                .DelToolStripMenuItem.Enabled = .ToolStripDelete.Enabled
                .SaveToolStripMenuItem.Enabled = .ToolStripSave.Enabled
                .CancelToolStripMenuItem.Enabled = .ToolStripCancel.Enabled
                .PrintToolStripMenuItem.Enabled = .ToolStripPrint.Enabled
                .ExportToolStripMenuItem.Enabled = .ToolStripImport.Enabled
                .ImportToolStripMenuItem.Enabled = .ToolStripExport.Enabled
                .FilterToolStripMenuItem.Enabled = .ToolStripFilter.Enabled
            End With

        Catch ex As Exception
            MsgBox("GetToolEnable:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

#End Region



    Private Sub Panel2_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel2.Paint

    End Sub

    Private Sub Splitter3_SplitterMoved(ByVal sender As System.Object, ByVal e As System.Windows.Forms.SplitterEventArgs) Handles Splitter3.SplitterMoved

    End Sub

    Private Sub dgrd1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrd1.CellContentClick

    End Sub

    Private Sub dgrd1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles dgrd1.Paint
        FormatDgrd(dgrd1, "Status")
    End Sub

    Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub
End Class
